package com.wangnian.task.service;

import com.wangnian.task.util.EmailUtil;
import com.wangnian.task.util.HttpUtil;
import com.wangnian.task.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2017/3/9.
 */
@Service
public class ExecuteTaskService {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private EmailUtil emailUtil;

    static final Logger logger = LoggerFactory.getLogger(ExecuteTaskService.class);

    @Retryable(value = {Exception.class}, maxAttempts = 20, backoff = @Backoff(delay = 1000, multiplier = 1.5))
    public void execute(String url, String bodyParameter, String identityKey, String description, boolean ifDisposable) throws Exception {
        try {
            String body = HttpUtil.post(url, bodyParameter);
            if ("SUCCESS".equals(body.toUpperCase())) {
                logger.info("调用成功=任务:{} 描述:{} 参数:{}", identityKey, description, bodyParameter);
                if (ifDisposable) {//如果是一次性的删掉
                    redisUtil.del(identityKey);
                }
            } else {
                throw new Exception("回调任务接口没有返回 SUCCESS");
            }
        } catch (Exception ex) {
            emailUtil.sendEmail("任务:" + identityKey + "描述:" + description + " 参数:" + bodyParameter + ",执行失败,等待重试,请检查是否在重启服务器或者是BUG");
            logger.warn("执行失败,等待重试=任务:{} 描述:{} 参数:{}", identityKey, description, bodyParameter, ex);
            throw new Exception(identityKey);
        }
    }

    @Recover
    public void recover(Exception e) {
        logger.warn("执行最终还是失败=任务Key:{}", e.getMessage());
        emailUtil.sendEmail("执行最终还是失败=任务Key:" + e.getMessage());
    }
}
